package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {

    @Autowired
    private WorkerCertificationAuditMapper workerCertificationAuditMapper;

    /**
     * 获取审核拒绝原因
     *
     * @return
     */
    @Override
    public WorkerCertificationAuditResDTO showRejectReason() {
        //根据当前用户id 结合 审核状态失败 从认证审核表查询
        Long userId = UserContext.currentUserId();
        LambdaQueryWrapper<WorkerCertificationAudit> wrapper = new LambdaQueryWrapper<WorkerCertificationAudit>()
                .eq(WorkerCertificationAudit::getServeProviderId, userId)
                .eq(WorkerCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                .orderByDesc(WorkerCertificationAudit::getAuditTime);
        List<WorkerCertificationAudit> workerCertificationAudits = workerCertificationAuditMapper.selectList(wrapper);
         if (ObjectUtil.isEmpty(workerCertificationAudits)){
            return null;
        }
        return BeanUtil.copyProperties(workerCertificationAudits.get(0), WorkerCertificationAuditResDTO.class);
    }

    /**
     * 审核服务人员认证信息
     *
     * @param id
     * @param certificationStatus
     * @param rejectReason
     */
    @Override
    public void review(Long id, Integer certificationStatus, String rejectReason) {
        //查询审核人员信息
        CurrentUserInfo userInfo = UserContext.currentUser();
        //更新服务人员认证审核表 根据认证申请id 查出申请记录
        WorkerCertificationAudit workerCertificationAudit = workerCertificationAuditMapper.selectById(id);
        if (ObjectUtil.isEmpty(workerCertificationAudit)){
            throw new ForbiddenOperationException("没有查询到数据");
        }
        //更新审核状态、审核人id、审核人name、审核时间、认证状态、拒绝原因
        //设置审核状态 已审核
        workerCertificationAudit.setAuditStatus(1);
        //设置审核人id
        workerCertificationAudit.setAuditorId(userInfo.getId());
        //设置审核人name
        workerCertificationAudit.setAuditorName(userInfo.getName());
        //设置审核时间
        workerCertificationAudit.setAuditTime(LocalDateTime.now());
        //设置认证状态
        workerCertificationAudit.setCertificationStatus(certificationStatus);
        if(ObjectUtil.isNotEmpty(rejectReason)){
            //设置拒绝原因
            workerCertificationAudit.setRejectReason(rejectReason);
        }
        //调用mapper更新
        workerCertificationAuditMapper.updateById(workerCertificationAudit);
        //更新服务人员认证信息表 认证时间 认证状态
        //根据认证审核表 获取到服务人员id
        //根据服务人员id 查出认证信息表相关信息
        WorkerCertification workerCertification = baseMapper.selectById(workerCertificationAudit.getServeProviderId());
        //设置认证时间
        workerCertification.setCertificationTime(workerCertificationAudit.getAuditTime());
        //设置认证状态
        workerCertification.setCertificationStatus(certificationStatus);
        //调用mapper更新
        baseMapper.updateById(workerCertification);
    }

    /**
     * 获取服务人员认证审核列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<WorkerCertificationAuditResDTO> getPage(WorkerCertificationAuditPageQueryReqDTO dto) {
        //设置分页参数
        Page<WorkerCertificationAudit> page = PageUtils.parsePageQuery(dto, WorkerCertificationAudit.class);

        //设置分页条件
        LambdaQueryWrapper<WorkerCertificationAudit> wrapper = new LambdaQueryWrapper<WorkerCertificationAudit>()
                .like(ObjectUtil.isNotEmpty(dto.getName()), WorkerCertificationAudit::getName, dto.getName())
                .eq(ObjectUtil.isNotEmpty(dto.getIdCardNo()), WorkerCertificationAudit::getIdCardNo, dto.getIdCardNo())
                .eq(ObjectUtil.isNotEmpty(dto.getAuditStatus()), WorkerCertificationAudit::getAuditStatus, dto.getAuditStatus())
                .eq(ObjectUtil.isNotEmpty(dto.getCertificationStatus()), WorkerCertificationAudit::getCertificationStatus, dto.getCertificationStatus());
        //分页查询
        Page<WorkerCertificationAudit> list = workerCertificationAuditMapper.selectPage(page, wrapper);
        if (ObjectUtil.isNull(list.getRecords())){
            throw new ForbiddenOperationException("没有查询到数据");
        }
        //返回结果
        return PageUtils.toPage(list, WorkerCertificationAuditResDTO.class);
    }

    /**
     * 提交认证审核
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitCertificationAudit(WorkerCertificationAuditAddReqDTO dto) {
        //获取当前登录用户
        Long userId = UserContext.currentUserId();
        //保存到服务人员认证信息表
        //copy dto
        WorkerCertification workerCertification = BeanUtil.copyProperties(dto, WorkerCertification.class);
        //补齐字段
        workerCertification.setId(userId);
        workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        //调用mapper保存
        WorkerCertification workerCertification1 = baseMapper.selectById(userId);
        if (ObjectUtil.isEmpty(workerCertification1)){
            baseMapper.insert(workerCertification);
        }
        else {
            baseMapper.update(workerCertification, new QueryWrapper<WorkerCertification>().eq("Id", userId));
        }
        //保存到服务人员认证审核表
        // copy dto
        WorkerCertificationAudit workerCertificationAudit = BeanUtil.copyProperties(dto, WorkerCertificationAudit.class);
        //补齐字段
        //服务人员id
        workerCertificationAudit.setServeProviderId(userId);
        //设置审核状态初始值 未审核(0 未审核 1 已审核)
        workerCertificationAudit.setAuditStatus(0);
        //设置认证状态
        workerCertificationAudit.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        //调用mapper保存
        workerCertificationAuditMapper.insert(workerCertificationAudit);
    }

    /**
     * 根据服务人员id更新
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新模型
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }
}
